//
//  CLLComposeView.swift
//  CLWeiNo
//
//  Created by DDC on 2017/10/19.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

import pop

class CLLComposeView: UIView {
    
    /// 定义一个block用于传递控制器名称
    fileprivate var completionSelectedBlock:((_ clsName:String?)->())?
    /// 属性控件
    @IBOutlet weak var scrollView: UIScrollView!
    /// 关闭按钮中心约束
    @IBOutlet weak var closeButtonCenterXCons: NSLayoutConstraint!
    /// 返回按钮中心约束
    @IBOutlet weak var returnButtonCenterXCons: NSLayoutConstraint!
    /// 返回按钮
    @IBOutlet weak var returnButton: UIButton!

    /// 按钮数组属性
    let buttonInfo = [["imageName":"tabbar_compose_book","title":"阅读","clsName":"CLLComposeViewController"],
                      ["imageName":"tabbar_compose_camera","title":"相机"],
                      ["imageName":"tabbar_compose_delete","title":"回收站"],
                      ["imageName":"tabbar_compose_envelope","title":"飞信"],
                      ["imageName":"tabbar_compose_friend","title":"朋友圈"],
                      ["imageName":"tabbar_compose_more","title":"更多","actionName":"clickMore"],
                      ["imageName":"tabbar_compose_transfer","title":"金币"],
                      ["imageName":"tabbar_compose_video","title":"视频"],
                      ["imageName":"tabbar_compose_wbcamera","title":"发现"],
                      ["imageName":"tabbar_compose_weibo","title":"心情"]]
    /// 从xib加载
    class func composeView() -> CLLComposeView{
        
        /// xib
        let nib = UINib(nibName: "CLLComposeView", bundle: nil)
        /// 从xib加载
        let v = nib.instantiate(withOwner: self, options: nil)[0] as! CLLComposeView
        /// 设置frame
        v.frame = UIScreen.main.bounds
        /// 设置按钮布局
        v.setUpUI()
        return v
    }
    func show(completion:@escaping (_ clsName:String?)->()) {
        
        /// 拿到跟控制器
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        /// 记录闭包--在需要的时候调用
        completionSelectedBlock = completion
        /// 添加
        vc.view.addSubview(self)
        /// 显示动画
        animationDisplay()
    }
    // MARK:  - 移除控件
    @IBAction func closeButtonClick(_ sender: Any) {
        
        // 显示向下动画
        animationDownEnd()
    }
    // MARK:  - 返回按钮
    @IBAction func returnButtonClick(_ sender: Any) {
        
        /// scrollview 返回到第一页
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        
        self.returnButtonCenterXCons.constant = 0
        self.closeButtonCenterXCons.constant = 0
        UIView.animate(withDuration: 0.25, animations: { 
            self.layoutIfNeeded()
            self.returnButton.alpha = 0
        }) { (_) in
            
            self.returnButton.alpha = 1
            self.returnButton.isHidden = true
        }
    }
}

// MARK: - 设置UI
fileprivate extension CLLComposeView {
    
    /// 设置布局
    func setUpUI(){
        /// 首先布局一下所有的控件,避免发生布局错乱
        layoutIfNeeded()
        /// 设置常量
        let rect = scrollView.bounds
        let width = UIScreen.main.bounds.width
        /// 循环创建视图
        for i in 0..<2 {
            
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i) * width, dy: 0))
            
            /// 添加按钮
            viewAddButton(view: v, idx: i * 6)
            scrollView.addSubview(v)
        }
        /// 设置scrollview的属性
        scrollView.contentSize = CGSize(width: 2 * width, height: rect.height)
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.isScrollEnabled = false
    }
    
    /// 将按钮添加到view上
    ///
    /// - Parameters:
    ///   - view: 视图
    ///   - idx: 按钮的索引
    func viewAddButton(view:UIView,idx:Int) {
        /// 设置按钮显示的数量
        let count = 6
        
        for i in idx..<(idx + count) {
            
            if i >= buttonInfo.count {
                break
            }
            /// 字典模型
            let dict = buttonInfo[i]
            /// 按钮所需要的属性
            guard let imageName = dict["imageName"],
                let title = dict["title"] else {
                    continue
            }
            /// 创建按钮
            let composeButton = CLLComposeButton.createComposeViewButton(imageName: imageName, title: title)
            composeButton.clsName = dict["clsName"]
            /// 添加点击事件
            if let actionName = dict["actionName"] {
                composeButton.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            } else {
                composeButton.addTarget(self, action: #selector(composeClick), for: .touchUpInside)
                
            }
            /// 添加按钮
            view.addSubview(composeButton)
            
        }
        /// 通过九宫格来布局按钮
        for (i,btn) in view.subviews.enumerated() {
            
            let itemWidth:CGFloat = 100
            let itemHeight:CGFloat = 100
            let margin = (UIScreen.main.bounds.width - itemWidth * 3)/4
            let col = i % 3
            let x = (CGFloat(col) + 1) * margin + CGFloat(col) * itemWidth
            let y = i > 2 ? (view.bounds.height - itemHeight) : 0
            btn.frame = CGRect(x: x, y: y, width: itemWidth, height: itemHeight)
            
        }
        
    }
    
    // MARK:  - 点击事件
    @objc func composeClick(selectedButton:CLLComposeButton) {
        print("点我了.")
        // 将控制器的名称字段传递给block
        // completionSelectedBlock?(selectedButton.clsName)
        // 执行变大变小动画
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        for(i,btn) in v.subviews.enumerated() {
            
            // 缩放动画
            let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            let scale = (selectedButton == btn) ? 2 : 0.5
            anim.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            anim.duration = 0.5
            btn.pop_add(anim, forKey: nil)
            // 显隐动画
            let dAnim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            dAnim.toValue = 0.2
            dAnim.duration = 0.5
            btn.pop_add(dAnim, forKey: nil)
            // 当点击第一个按钮跳转控制器的闭包调用
            if i == 0 {
                anim.completionBlock = { _, _ in
                    
                    self.completionSelectedBlock?(selectedButton.clsName)
                }
            }
        }
        
    }
    @objc func clickMore(){
        print("点击了更多")
        // 滚动scrollview到第二页
        let offset = CGPoint(x: scrollView.bounds.width, y: 0)
        scrollView.setContentOffset(offset, animated: true)
        // 设置底部返回/关闭按钮细节
        returnButton.isHidden = false
        let margin = scrollView.bounds.width / 6
        self.returnButtonCenterXCons.constant = -margin
        self.closeButtonCenterXCons.constant = margin
        
        // 添加动画
        UIView.animate(withDuration: 0.25) { 
            self.layoutIfNeeded()
        }
        
    }
    
}

// MARK: - 动画方法
fileprivate extension CLLComposeView {
    
    /// 初始由隐藏到显示动画
    func animationDisplay(){
        
        // 起始显隐动画
        let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        // 设置anim的属性
        anim.fromValue = 0
        anim.toValue = 1
        anim.duration = 0.5
        pop_add(anim, forKey: nil)
        // 显示的同时加载向上动画
        animationUpBegin()
    }
    /// 向上动画
    func animationUpBegin(){
        
        // 获取当前页面
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        // 遍历页面上的按钮
        for(i,btn) in v.subviews.enumerated() {
            
            // 重力动画
            let anim:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            // anim动画属性
            anim.fromValue = btn.center.y + 400
            anim.toValue = btn.center.y
            anim.springSpeed = 8
            anim.springBounciness = 10
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            btn.layer.pop_add(anim, forKey: nil)
        }
        
    }
    /// 向下动画
    func animationDownEnd(){
        
        // 获取当前页面
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        // 遍历视图上的自视图--倒序
        for(i,btn) in v.subviews.enumerated().reversed(){
            
            // 创建动画
            let anim:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            // 设置动画属性
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + 400
            anim.springSpeed = 8
            anim.springBounciness = 10
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            // 添加动画
            btn.layer.pop_add(anim, forKey: nil)
            
            if i == 0 {
                // 当最后一个按钮落下的时候,隐藏composes视图并移除
                anim.completionBlock = {_,_ in
                    
                    self.hideComposeViewAndRemove()
                    
                }
            }
        }
        
    }
    
    /// 隐藏composes视图并移除
    func hideComposeViewAndRemove(){
        // 初始化动画
        let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        // 设置动画属性
        anim.fromValue = 1
        anim.toValue = 0
        anim.duration = 0.25
        pop_add(anim, forKey: nil)
        // 移除composeView
        anim.completionBlock = { _, _ in
            
            self.removeFromSuperview()
        }
    }
    
}
